package com.lzj.jiangxindaojia.view.login;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ifaa.sdk.api.AuthenticatorManager;
import com.ifaa.sdk.auth.AuthenticatorCallback;
import com.ifaa.sdk.auth.Constants;
import com.ifaa.sdk.auth.IAuthenticator;
import com.ifaa.sdk.auth.message.AuthenticatorMessage;
import com.ifaa.sdk.auth.message.AuthenticatorResponse;
import com.lzj.jiangxindaojia.MainActivity;
import com.lzj.jiangxindaojia.R;
import com.lzj.jiangxindaojia.base.BaseActivity;
import com.lzj.jiangxindaojia.bean.FingerRegistInit;
import com.lzj.jiangxindaojia.bean.ResultCode;
import com.lzj.jiangxindaojia.http.HttpAction;
import com.lzj.jiangxindaojia.http.HttpCallBack;
import com.lzj.jiangxindaojia.http.HttpConstans;
import com.lzj.jiangxindaojia.http.HttpUtil;
import com.lzj.jiangxindaojia.utils.GsonUtil;
import com.lzj.jiangxindaojia.utils.LogUtils;
import com.lzj.jiangxindaojia.utils.MD5;
import com.lzj.jiangxindaojia.utils.SharePreferenceUtil;
import com.lzj.jiangxindaojia.utils.Utils;
import com.lzj.jiangxindaojia.view.login.ali.FingerPrintAuthActivity;
import com.lzj.jiangxindaojia.view.login.ali.FingerPrintToast;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by lizj on 2017/12/5.
 */

public class ZhiwenLoginActivity extends BaseActivity implements HttpCallBack{
    private TextView tv_tile,btn_pwdlogin;
    private ImageView iv_left;
    private LinearLayout ll_left;
    Button btn_zhiwenlogin;
    private String user_id = "";
    private HttpCallBack httpcallback;
    @Override
    protected void initData() {
        super.initData();
        this.tv_tile = ((TextView)findViewById(R.id.tv_tile));
        this.iv_left = ((ImageView)findViewById(R.id.iv_left));
        this.ll_left = ((LinearLayout)findViewById(R.id.ll_left));
        this.tv_tile.setText(R.string.login_zhiwenlogin);
        this.ll_left.setVisibility(View.VISIBLE);
        iv_left.setImageResource(R.mipmap.back);
        this.btn_zhiwenlogin = ((Button)findViewById(R.id.btn_zhiwenlogin));
        this.btn_pwdlogin = ((TextView)findViewById(R.id.btn_pwdlogin));

        user_id = SharePreferenceUtil.getData(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.USER_ID);

        httpcallback = this;

    }

    @Override
    protected void requestServer() {
        super.requestServer();
    }

    @Override
    protected void setListener() {
        super.setListener();
        btn_zhiwenlogin.setOnClickListener(this);
        btn_pwdlogin.setOnClickListener(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_zhiwenlogin;
    }



    private int authType = Constants.TYPE_FINGERPRINT;
    public  static IAuthenticator authenticator;
    private HashMap paramMap;
    private String secData = "";
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_zhiwenlogin:

                if (AuthenticatorManager.isSupportIFAA(this, authType)) {
                    authenticator = AuthenticatorManager.create(this, authType, "JXDJ");
                    if(authenticator.hasEnrolled()){
                        String token = SharePreferenceUtil.getData(this,SharePreferenceUtil.TOKENFILE,SharePreferenceUtil.REGIST_LOGINTOKEN);
                        if(authenticator.checkUserStatus(token)==2){//0没开通 2开通了 3开通了本地模板删除了
                            /**
                             * 获得授权数据
                             */
                            String info = AuthenticatorManager.getAuthData(this, SharePreferenceUtil.getData(this,SharePreferenceUtil.USERINFO,SharePreferenceUtil.USER_ID));
                            secData = info;
                            LogUtils.log("secData:  " + info);

                            paramMap = new HashMap();
                            paramMap.put("type", "3");
                            paramMap.put("app_id", HttpConstans.appid);
                            paramMap.put("channel_number", HttpConstans.qdnumber);
                            paramMap.put("verify_token", token);
                            paramMap.put("sec_data", secData);
                            paramMap.put("ifaa_version", "2.0");
                            paramMap.put("sign", MD5.md5(MD5.createSignString(paramMap) + HttpConstans.KEY));
                            HttpUtil.getInstance(this).postAsynHttp(HttpConstans.BASEURL+HttpConstans.FINGER_REGIST_INIT, paramMap, this, this, HttpAction.FINGER_CHECK_INIT);
                        }
                    }
                }else{
                    Toast.makeText(this, "This device not support IFAA", Toast.LENGTH_LONG).show();
                }

                break;
            case R.id.btn_pwdlogin:
                Utils.goNextActivity(this,PwdLoginActivity.class);
                break;
            case R.id.ll_left:
                break;
        }
    }
    private FingerRegistInit fingerRegistInit;
    @Override
    public <T> void onSuccess(String  result, String action) {
                switch (action){
                    case HttpAction.FINGER_CHECK_INIT:
                        fingerRegistInit =  GsonUtil.GsonToBean(result, FingerRegistInit.class);
                        if (ResultCode.SUCCESS.equals(fingerRegistInit.getStatus())) {
                            startFPActivity(false);
                            AuthenticatorMessage requestMessage = new AuthenticatorMessage(AuthenticatorMessage.MSG_AUTHENTICATOR_REQUEST, 2);
                            requestMessage.setData(fingerRegistInit.getData().getContent());
                            authenticator.process(requestMessage, regCallback);
                        } else {
                            Utils.showToast(this, fingerRegistInit.getMsg());
                        }
                        break;
                    case HttpAction.FINGER_CHECK_LOGIN:
                        try{
                            JSONObject jsonObject = new JSONObject(result);
                            String status = jsonObject.getString("status");
                            String msg = jsonObject.getString("msg");
                            String data = jsonObject.getString("data");
                            if (ResultCode.SUCCESS.equals(status)) {
                                String token = data;
                                SharePreferenceUtil.keepDate(this,SharePreferenceUtil.TOKENFILE,SharePreferenceUtil.REGIST_LOGINTOKEN,token);
                                Utils.goNextActivity(ZhiwenLoginActivity.this, MainActivity.class);
                            } else {
                                Utils.showToast(this, msg);
                            }
                            SettingZwLoginActivity.FingerprintBroadcastUtil.sendIdentifyStatusChangeMessage(ZhiwenLoginActivity.this, 0);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        break;
                }
    }


    private AuthenticatorCallback regCallback = new AuthenticatorCallback() {
        @Override
        public void onStatus(int status) {
            SettingZwLoginActivity.FingerprintBroadcastUtil.sendIdentifyStatusChangeMessage(ZhiwenLoginActivity.this, status);
        }

        @Override
        public void onResult(final AuthenticatorResponse response) {
            String data = response.getData();
            LogUtils.log("reg respone info:" + data);
            LogUtils.log("response:" + response.toString());
            LogUtils.log("response.getResult() :" + response.getResult() );
            if (response.getResult() == AuthenticatorResponse.RESULT_SUCCESS) {
//                IFAAFingerprintOpenAPI.getInstance().sendRegResponeAsyn(data, secData, callback);
                paramMap = new HashMap();
                paramMap.put("type", "4");
                paramMap.put("verify_type", "login_verify");
                paramMap.put("app_id", HttpConstans.appid);
                paramMap.put("channel_number", HttpConstans.qdnumber);
                paramMap.put("user_id", user_id);
                paramMap.put("ifaf_message", data);
                paramMap.put("sec_data", secData);
                paramMap.put("subAction", "verify");
                paramMap.put("sign", MD5.md5(MD5.createSignString(paramMap) + HttpConstans.KEY));
                HttpUtil.getInstance(ZhiwenLoginActivity.this).postAsynHttp(HttpConstans.BASEURL+HttpConstans.FINGER_LOGIN_REGIST, paramMap, ZhiwenLoginActivity.this, httpcallback, HttpAction.FINGER_CHECK_LOGIN);
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new FingerPrintToast(ZhiwenLoginActivity.this, FingerPrintToast.ST_REGFAIL).show("reg fail:" + response.getResult());
                        SettingZwLoginActivity.FingerprintBroadcastUtil.sendIdentifyStatusChangeMessage(ZhiwenLoginActivity.this, 0);
                    }
                });
            }
        }
    };

    public void startFPActivity(boolean isAuthenticate) {
        Intent intent = new Intent();
//        if (isAuthenticate) {
//            intent.putExtra(AuthenticatorMessage.KEY_OPERATIONT_TYPE,
//                    AuthenticatorMessage.MSG_AUTHENTICATOR_REQUEST);
//        }
        intent.setClass(this, FingerPrintAuthActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);

    }

}
